/**
 * Foxit Software Inc.
 * Copyright(C) 2005-2014, all rights reserved.
 * The following code is copyrighted and contains proprietary information
 * and trade secrets of Foxit Software Inc.

 * Description: PDFBookmarkLoader
 * Author: shaojie zhuo
 * Update: shaojie zhuo (2014-06-04 15:57)
 */
define(function (require, exports, module) {
    var ImageEngine = WebPDF.ImageEngine;

    /**
     * Annotation加载器
     * @constructor
     * @private
     */
    ImageEngine.PDFBookmarkLoader = function () {
        var _remainedRetryCount = WebPDF.Config.defaults.requestRetryCount;
        var _self = this;

        this.asyncLoadPDFBookmark = function(readerApp, pdfDocument, doneHandler, failedHandler)
        {
            if(!$.isFunction(doneHandler) || !$.isFunction(failedHandler)){
                $.error("both 'doneHandler' and 'failedHandler' must be function.");
            }
            if (_remainedRetryCount <= 0) {
                console.error('Maximum number of retries exceeded for getBookmarkData request.');
                failedHandler(null);
                return;
            }

            var requestData =  { };
            requestData.formMode = readerApp.isFormMode();
            requestData.s3Key = readerApp.getFileID();
            $.ajax({
                url: readerApp.getOptions().url + "bookmarks",
                dataType: 'json',
                data: requestData,
                contentType:"application/x-www-form-urlencoded",
                success: function (response) {
                    var error = response.error;
                    if (error != 0) {
                        if (WebPDF.Common.isNeedRetry(response.status)) {
                            var interval = WebPDF.AjaxRetryManager.getNextBookmarkDataRequestInterval(
                                readerApp.getMainView().getDocView().getPageCount());
                            _remainedRetryCount--;
                            setTimeout(function () { _self.asyncLoadPDFBookmark(readerApp, pdfDocument, doneHandler, failedHandler); }, interval);
                            return;
                        }
                        else {
                            console.error('Get bookmark data error:' + error);
                            failedHandler(response);
                            return;
                        }
                    }
                    //try {
                        doneHandler($.parseJSON(response.BookmarkInfo));
                   // }
                    //catch (ex) {
                     //   console.error(ex);
                     //   failedHandler(response);
                     //   return false;
                    //}
                },
                error: function () {
                    failedHandler(null);
                }
            });
        };
    };
});